const app = getApp()

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    showCustomize: false,
    avatarUrl: '',
    nickName: '',
    favorites: [],
    history: [],
    stats: {
      totalAnswered: 0,
      correctRate: 0,
      favoriteCount: 0
    }
  },

  onLoad() {
    this.checkUserInfo()
    this.loadUserData()
  },

  onShow() {
    this.loadUserData()
  },

  // 检查用户登录状态
  checkUserInfo() {
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo && userInfo.nickName) {
      // 格式化登录时间
      const loginTimeText = userInfo.loginTime ? 
        this.formatLoginTime(userInfo.loginTime) : '最近登录'
      
      this.setData({
        userInfo: {
          ...userInfo,
          loginTimeText
        },
        hasUserInfo: true
      })
      app.globalData.userInfo = userInfo
    }
  },

  // 格式化登录时间
  formatLoginTime(timestamp) {
    const now = Date.now()
    const diff = now - timestamp
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    
    if (days === 0) {
      return '今天登录'
    } else if (days === 1) {
      return '昨天登录'
    } else if (days < 7) {
      return `${days}天前登录`
    } else {
      return '很久之前登录'
    }
  },

  // 微信登录
  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        const { nickName, avatarUrl } = res.userInfo
        
        // 检查是否是有效的用户信息
        if (nickName !== '微信用户' && avatarUrl && !avatarUrl.includes('default')) {
          // 使用微信提供的真实信息
          this.saveUserInfo({
            nickName,
            avatarUrl,
            source: 'wechat',
            loginTime: Date.now()
          })
        } else {
          // 微信返回的是默认信息，让用户自定义
          this.showCustomizeProfile({
            defaultNickName: nickName === '微信用户' ? '' : nickName,
            defaultAvatarUrl: avatarUrl
          })
        }
      },
      fail: () => {
        // 用户拒绝授权，显示自定义界面
        wx.showToast({
          title: '可以自定义头像昵称',
          icon: 'none'
        })
        this.showCustomizeProfile()
      }
    })
  },

  // 显示自定义信息界面
  showCustomizeProfile(options = {}) {
    this.setData({
      showCustomize: true,
      avatarUrl: options.defaultAvatarUrl || '',
      nickName: options.defaultNickName || ''
    })
  },

  // 取消自定义
  cancelCustomize() {
    this.setData({
      showCustomize: false,
      avatarUrl: '',
      nickName: ''
    })
  },

  // 选择头像
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    this.setData({ avatarUrl })
  },

  // 输入昵称
  onNicknameChange(e) {
    const nickName = e.detail.value.trim()
    this.setData({ nickName })
  },

  // 保存自定义信息
  saveCustomInfo() {
    const { avatarUrl, nickName } = this.data
    
    if (!nickName.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return
    }
    
    this.saveUserInfo({
      nickName: nickName.trim(),
      avatarUrl: avatarUrl || '/images/default-avatar.svg',
      source: 'custom',
      loginTime: Date.now()
    })
  },

  // 保存用户信息并合并数据
  saveUserInfo(userInfo) {
    // 合并游客数据
    this.mergeGuestData()
    
    // 格式化登录时间
    const loginTimeText = this.formatLoginTime(userInfo.loginTime)
    
    const finalUserInfo = {
      ...userInfo,
      loginTimeText
    }
    
    // 保存到本地和全局
    wx.setStorageSync('userInfo', finalUserInfo)
    app.globalData.userInfo = finalUserInfo
    
    this.setData({
      userInfo: finalUserInfo,
      hasUserInfo: true,
      showCustomize: false,
      avatarUrl: '',
      nickName: ''
    })
    
    wx.showToast({
      title: '登录成功',
      icon: 'success'
    })
    
    // 重新加载数据
    this.loadUserData()
  },

  // 合并游客数据
  mergeGuestData() {
    // 这里可以将游客的答题记录、收藏等数据关联到用户账号
    // 由于是本地存储，数据已经存在，不需要额外处理
    // 如果有服务端，这里应该上传数据到服务器
    console.log('合并游客数据到用户账号')
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '确认退出',
      content: '退出登录后将清除用户信息，但保留答题记录',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('userInfo')
          app.globalData.userInfo = null
          
          this.setData({
            userInfo: {},
            hasUserInfo: false,
            showCustomize: false
          })
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          })
        }
      }
    })
  },

  // 加载用户数据
  loadUserData() {
    this.loadFavorites()
    this.loadHistory()
    this.calculateStats()
  },

  // 加载收藏题目
  loadFavorites() {
    const favorites = wx.getStorageSync('favorites') || []
    this.setData({ favorites })
  },

  // 加载做题历史
  loadHistory() {
    const answerHistory = wx.getStorageSync('answerHistory') || []
    
    // 转换为显示格式
    const history = answerHistory.map(item => ({
      ...item,
      dateString: this.formatDate(item.timestamp)
    })).slice(0, 10) // 只显示最近10条
    
    this.setData({ history })
  },

  // 格式化日期
  formatDate(timestamp) {
    const date = new Date(timestamp)
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const itemDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
    
    if (itemDate.getTime() === today.getTime()) {
      return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    } else if (itemDate.getTime() === today.getTime() - 24 * 60 * 60 * 1000) {
      return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    } else {
      return `${date.getMonth() + 1}月${date.getDate()}日`
    }
  },

  // 计算统计数据
  calculateStats() {
    const answerHistory = wx.getStorageSync('answerHistory') || []
    const favorites = wx.getStorageSync('favorites') || []
    
    const totalAnswered = answerHistory.length
    const correctCount = answerHistory.filter(item => item.isCorrect).length
    const correctRate = totalAnswered > 0 ? Math.round((correctCount / totalAnswered) * 100) : 0
    
    this.setData({
      stats: {
        totalAnswered,
        correctRate,
        favoriteCount: favorites.length
      }
    })
  },

  // 跳转到题目详情
  goToQuestionDetail(e) {
    const { id, bankId } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/question-detail/question-detail?id=${id}&bankId=${bankId}`
    })
  },

  // 取消收藏
  removeFavorite(e) {
    const { id } = e.currentTarget.dataset
    let favorites = wx.getStorageSync('favorites') || []
    
    favorites = favorites.filter(item => item.id !== id)
    wx.setStorageSync('favorites', favorites)
    
    this.setData({ favorites })
    this.calculateStats()
    
    wx.showToast({
      title: '已取消收藏',
      icon: 'success'
    })
  },

  // 清空所有收藏
  clearAllFavorites() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有收藏的题目吗？',
      success: (res) => {
        if (res.confirm) {
          wx.setStorageSync('favorites', [])
          this.setData({ favorites: [] })
          this.calculateStats()
          
          wx.showToast({
            title: '已清空收藏',
            icon: 'success'
          })
        }
      }
    })
  },

  // 删除历史记录项
  removeHistoryItem(e) {
    const { id } = e.currentTarget.dataset
    let answerHistory = wx.getStorageSync('answerHistory') || []
    
    answerHistory = answerHistory.filter(item => item.id !== id)
    wx.setStorageSync('answerHistory', answerHistory)
    
    this.loadHistory()
    this.calculateStats()
    
    wx.showToast({
      title: '已删除',
      icon: 'success'
    })
  },

  // 清空所有历史
  clearAllHistory() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有做题历史吗？',
      success: (res) => {
        if (res.confirm) {
          wx.setStorageSync('answerHistory', [])
          this.setData({ history: [] })
          this.calculateStats()
          
          wx.showToast({
            title: '已清空历史',
            icon: 'success'
          })
        }
      }
    })
  },

  // 查看全部历史
  viewAllHistory() {
    // 这里可以跳转到历史记录详情页
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  }
})